package standalone;
import java.io.File;
import java.util.List;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.Scheduler;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import engine.Engine;
import engine.dataobjects.MailItemInstance;
import engine.services.IMailItemsResource;
import engine.services.IMailService;



public class Main {

    static Log log = null;
    static final String DEBUG_OPTION = "debug";
    static final String NOW_OPTION = "now";
    static final String HELP_OPTION = "help";
	
	boolean isDebug = false;
	boolean isNow = false;

    Scheduler scheduler;
    ApplicationContext context;
    
    /***
     * add options:
     * 
     * -debug
     * -filter [filter for name]
     * -now
     * -help
     * 
     * @param args
     */
	public static void main(String[] args){
		File metainf = new File("META-INF");
		if (!metainf.exists()) {
			String userDirPath = System.getProperty("user.dir");
			File userDir = new File(userDirPath);
			
			File resources =  new File(userDir.getParentFile().getAbsolutePath()+ File.separator+ "resources");
			if (resources.exists()) {
				System.setProperty("user.dir", userDir.getParentFile().getAbsolutePath()+ File.separator+ "resources");					
				System.setProperty("log4j.configuration","file:/"+userDir.getParentFile().getAbsolutePath()+ File.separator+ "resources/META-INF/log4j.xml");
				log = LogFactory.getLog(Main.class);
				log.info("Current dir set to: " + System.getProperty("user.dir"));
			} else {
				log = LogFactory.getLog(Main.class);
				log.warn("Current Dir does not contain META-INF");
			}
		}
		log.info("############### run context data #############");
		log.info("Current dir: " + System.getProperty("user.dir"));
		new Main(args, "file:**/META-INF/ScheduledMailerApplicationContext.xml", 300L * 1000L);
	}

	public Main(String[] args, String applicationContextFile, long debugSleepTime) {

		if (log == null) {
		    log = LogFactory.getLog(Main.class);
		}
		Options options = new Options();
		options.addOption(DEBUG_OPTION, false, "Running in debug mode");
		options.addOption(NOW_OPTION, false, "Triggering all the jobs once on the run");
		options.addOption(HELP_OPTION, false, "help");
		
		try {

			CommandLineParser parser = new GnuParser();
			CommandLine line = parser.parse( options, args );
			if (args != null) {
				if (line.hasOption(HELP_OPTION)) {
					HelpFormatter formatter = new HelpFormatter();
					formatter.printHelp( "MailPusher", options );					
					return;
				}
				if (line.hasOption(DEBUG_OPTION)) {
					isDebug = true;
				} 
				if (line.hasOption(NOW_OPTION)) {
					// this will call the trigger for right now
					isNow = true;					
				}

			}

			log.info("############### reading app context : "+ applicationContextFile+" #############");
			context = new FileSystemXmlApplicationContext(applicationContextFile);	

			if (isDebug) {
				IMailService mailservice = (IMailService)context.getBean("mailService");
				mailservice.setDebugMode();
			}

			((Engine)context.getBean("engine")).start(isNow);
			List<MailItemInstance<?>> items = ((IMailItemsResource)context.getBean("configResource")).getActiveMailItemInstances();
			((Engine)context.getBean("engine")).initMailItems(items);
			
	        if (isDebug) {
		        scheduler = (Scheduler)context.getBean("scheduler");

		        log.info("Running in debug mode for "+ debugSleepTime/(60*1000)+" minutes only ... ");
		        // wait five minutes to give our jobs a chance to run
		        try {
		            Thread.sleep(debugSleepTime); 
		        } catch (Exception e) {
		        	//
		        }
	        	log.info("Shutting down the scheduler");
		        scheduler.shutdown();
		        log.info("Done.");
	        }
	        
	        log.info("################################# Mailer is running. ######################################");
		} catch (Exception e) {
			log.error(e.getMessage());
			log.error("Could not start scheduler", e);
			System.exit(-1);
		}
	}
	
	
}
